package com.ocm.commerceinteraction.util.helper;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.TypedValue;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;

/**
 * 获取屏幕公共方法
 * 
 * @author tl
 */
public class ScreenHelper
{
	/**
	 * dp?px
	 *
	 * @param context
	 * @param dpVal
	 * @return
	 */
	public static int dp2px(Context context, float dpVal)
	{
		return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
		      dpVal,context.getResources().getDisplayMetrics());
	}

	/**
	 * sp?px
	 *
	 * @param context
	 * @param spVal
	 * @return
	 */
	public static int sp2px(Context context, float spVal)
	{
		return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP,
		        spVal,context.getResources()
		                                                                                                .getDisplayMetrics());
	}

	/**
	 * px?dp
	 *
	 * @param context
	 * @param pxVal
	 * @return
	 */
	public static float px2dp(Context context, float pxVal)
	{
		final float scale = context.getResources().getDisplayMetrics().density;
		return (pxVal / scale);
	}

	/**
	 * px?sp
	 * 
	 * @param pxVal
	 * @return
	 */
	public static float px2sp(Context context, float pxVal)
	{
		return (pxVal / context.getResources().getDisplayMetrics().scaledDensity);
	}

	/**
	 * 获取屏幕宽
	 * 
	 * @param context
	 * @return
	 */
	public static int getScreenWidth(Context context)
	{
		WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
		DisplayMetrics outMetrics = new DisplayMetrics();
		wm.getDefaultDisplay().getMetrics(outMetrics);
		return outMetrics.widthPixels;
	}

	/**
	 * 获取屏幕宽
	 * 
	 * @param context
	 * @return
	 */
	public static int getScreenHeight(Context context)
	{
		WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
		DisplayMetrics outMetrics = new DisplayMetrics();
		wm.getDefaultDisplay().getMetrics(outMetrics);
		return outMetrics.heightPixels;
	}

	/**
	 * 获取状态栏高
	 * 
	 * @param context
	 * @return
	 */
	public static int getStatusHeight(Context context)
	{
		int statusHeight = -1;
		try
		{
			Class<?> clazz = Class.forName("com.android.internal.R$dimen");
			Object object = clazz.newInstance();
			int height = Integer.parseInt(clazz.getField("status_bar_height")
			       .get(object).toString());
			statusHeight = context.getResources().getDimensionPixelSize( height);
		} 
		catch (Exception e)
		{
			e.printStackTrace();
		}
		return statusHeight;
	}

	/**
	 * 改变字体
	 * 
	 * @param path
	 *              路径
	 */
	public static void changeFonts(ViewGroup root, String path, Activity act)
	{
		Typeface tf = Typeface.createFromAsset(act.getAssets(), path);
		for (int i = 0; i < root.getChildCount(); i++)
		{
			View v = root.getChildAt(i);
			if (v instanceof TextView)
			{
				((TextView) v).setTypeface(tf);
			}
			else if (v instanceof Button)
			{
				((Button) v).setTypeface(tf);
			}
			else if (v instanceof EditText)
			{
				((EditText) v).setTypeface(tf);
			}
			else if (v instanceof ViewGroup)
			{
				changeFonts((ViewGroup) v, path, act);
			}
		}
	}

	/**
	 * 改变字体大小
	 */
	public static void changeTextSize(ViewGroup root, int size, Activity act)
	{
		for (int i = 0; i < root.getChildCount(); i++)
		{
			View v = root.getChildAt(i);
			if (v instanceof TextView)
			{
				((TextView) v).setTextSize(size);
			}
			else if (v instanceof Button)
			{
				((Button) v).setTextSize(size);
			}
			else if (v instanceof EditText)
			{
				((EditText) v).setTextSize(size);
			}
			else if (v instanceof ViewGroup)
			{
				changeTextSize((ViewGroup) v, size, act);
			}
		}
	}

	/**
	 * 改变View宽高
	 */
	public static void changeWH(View v, int W, int H)
	{
		ViewGroup.LayoutParams params = (ViewGroup.LayoutParams) v
		                                                .getLayoutParams();
		params.width = W;
		params.height = H;
		v.setLayoutParams(params);
	}

	/**
	 * 改变高度
	 */
	public static void changeH(View v, int H)
	{
		ViewGroup.LayoutParams params = (ViewGroup.LayoutParams) v.getLayoutParams();
		params.height = H;
		v.setLayoutParams(params);
	}

	/**
	 * 改变宽度
	 */
	public static void changeW(View v, int w)
	{
		ViewGroup.LayoutParams params = (ViewGroup.LayoutParams) v.getLayoutParams();
		params.width = w;
		v.setLayoutParams(params);
	}

	/**
	 * 改变字体长度
	 * 
	 * @param str
	 * @param textsize
	 * @return
	 */
	public static float getTextWidthFontPx(String str, float textsize)
	{
		Paint mPaint = new Paint();
		mPaint.setTextSize(textsize);
		return str.length() * mPaint.getFontSpacing();
	}

	/**
	 * 重新计算listView的高度
	 * 
	 * @param listView
	 */
	public static void setListViewHeightBasedOnChildren(ListView listView)
	{
		ListAdapter listAdapter = listView.getAdapter();
		if (listAdapter == null)
		{
			// pre-condition
			return;
		}

		int totalHeight = 0;
		for (int i = 0; i < listAdapter.getCount(); i++)
		{
			View listItem = listAdapter.getView(i, null, listView);
			listItem.measure(0, 0);
			totalHeight += listItem.getMeasuredHeight();
		}

		ViewGroup.LayoutParams params = listView.getLayoutParams();
		params.height = totalHeight+ (listView.getDividerHeight() * (listAdapter.getCount() - 1));
		listView.setLayoutParams(params);
	}
	/**
	 * 动态设置gridview 高度
	 * @param gridView 
	 * @param size item数量 
	 */
	public static void setGridViewHeightBasedOnChildren(GridView gridView) {
		// 获取listview的adapter

		ListAdapter listAdapter = gridView.getAdapter();
		if (listAdapter == null) {
			return;
		}
		// 固定列宽，有多少列
		int col = 3;// listView.getNumColumns();
		int totalHeight = 0;
//			// 获取listview的每一个item
			View listItem = listAdapter.getView(0, null, gridView);
//			listItem.measure(0, 0);
			// 获取item的高度和
			totalHeight = listItem.getMeasuredHeight();
		int rowCount = listAdapter.getCount() / col;
		if (0 != listAdapter.getCount() % col) {
			rowCount = rowCount + 1;
		}

		// 获取listview的布局参数
		ViewGroup.LayoutParams params = gridView.getLayoutParams();
		// 设置高度
		params.height = totalHeight * rowCount;
		gridView.setLayoutParams(params);
	}

	/**
	 * 获取半径
	 * 
	 * @param longitude1
	 * @param latitude1
	 * @return
	 */
	private static final double EARTH_RADIUS = 6378137.0;

	public static double getDistance(double longitude1, double latitude1,double longitude2,double latitude2)
	{
		double Lat1 = rad(latitude1);
		double Lat2 = rad(latitude2);
		double a = Lat1 - Lat2;
		double b = rad(longitude1) - rad(longitude2);
		double s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2)
		          + Math.cos(Lat1)* Math.cos(Lat2)* Math.pow(Math.sin(b / 2),2)));
		s = s * EARTH_RADIUS;
		s = Math.round(s * 10000) / 10000;
		return s;
	}

	private static double rad(double d)
	{
		return d * Math.PI / 180.0;
	}

	/**
	 * 
	 */
	public static String double_convert(double value)
	{
		long l1 = Math.round(value * 100);// ��������
		double ret = l1 / 100.0;// ע�⣺ʹ��100.0,���� 100
		if (ret - (int) ret == 0)
		{
			return (int) ret + "";
		}
		else
		{
			return ret + "";
		}
	}

	/**
	 *
	 * @param activity
	 * @return
	 */
	public static Bitmap snapShotWithStatusBar(Activity activity)
	{
		View view = activity.getWindow().getDecorView();
		view.setDrawingCacheEnabled(true);
		view.buildDrawingCache();
		Bitmap bmp = view.getDrawingCache();
		int width = getScreenWidth(activity);
		int height = getScreenHeight(activity);
		Bitmap bp = null;
		bp = Bitmap.createBitmap(bmp, 0, 0, width, height);
		view.destroyDrawingCache();
		return bp;
	}

	/**
	 *
	 * @param activity
	 * @return
	 */
	public static Bitmap snapShotWithoutStatusBar(Activity activity)
	{
		View view = activity.getWindow().getDecorView();
		view.setDrawingCacheEnabled(true);
		view.buildDrawingCache();
		Bitmap bmp = view.getDrawingCache();
		Rect frame = new Rect();
		activity.getWindow() .getDecorView().getWindowVisibleDisplayFrame(frame);
		int statusBarHeight = frame.top;

		int width = getScreenWidth(activity);
		int height = getScreenHeight(activity);
		Bitmap bp = null;
		bp = Bitmap.createBitmap(bmp, 0, statusBarHeight, width, height - statusBarHeight);
		view.destroyDrawingCache();
		return bp;
	}
	public static int getAndroidSDKVersion() {
        int version = 0;
        try {
            version = Integer.valueOf(android.os.Build.VERSION.SDK);
        } catch (NumberFormatException e) {
        }
        return version;
    }
	
	// 获取指定Activity的截屏，保存到png文件
//	String filenameTemp =FileUtil.getImageDirectory().getPath();
	
//	private static View getContentView(Activity activity,MainFitnessIndexFragment fragment)
//	{
//        ViewGroup view = (ViewGroup) activity.getWindow().getDecorView();
//        fragment = (MainFitnessIndexFragment) view.getTag(fragment.getTag());
//        getVisibleFragment(activity);
//        
//        return fragment;
//    }
//	
//	public static Fragment getVisibleFragment(Activity activity)
//	{
//	    FragmentManager fragmentManager = activity.getSupportFragmentManager();
//	    List<Fragment> fragments = fragmentManager.getFragments();
//	    for(Fragment fragment : fragments){
//	        if(fragment != null && fragment.isVisible())
//	            return fragment;
//	    }
//	    return null;
//	}

	
//	public static Bitmap takeScreenShot(Activity activity,MainFitnessIndexFragment fragment) 
//	{
//		// View是你需要截图的View
//		ViewGroup view = (ViewGroup) activity.getWindow().getDecorView();
////		HIFitApp.getContext();
////		View view = fragment;
//		view.setDrawingCacheEnabled(true);
//		view.buildDrawingCache();
//		Bitmap b1 = view.getDrawingCache();
//
//		// 获取状态栏高度
////		Rect frame = new Rect();
////		activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
////		int statusBarHeight = frame.top;
//		int statusBarHeight = getStatusHeight(activity);
//		Log.i("TAG", "" + statusBarHeight);
//
//		// 获取屏幕长和高
//		int width = getScreenWidth(activity);
//		int height = getScreenHeight(activity);
//		// 去掉标题栏
//		// Bitmap b = Bitmap.createBitmap(b1, 0, 25, 320, 455);
//		Bitmap b = Bitmap.createBitmap(b1, 0, statusBarHeight, width, height- statusBarHeight);
//		view.destroyDrawingCache();
//		return b;
//	}
//	
//	
//	public static Bitmap takeScreenShot(Activity activity) 
//	{
//		// View是你需要截图的View
//		View view = activity.getWindow().getDecorView();
//		view.setDrawingCacheEnabled(true);
//		view.buildDrawingCache();
//		Bitmap b1 = view.getDrawingCache();
//
//		// 获取状态栏高度
////		Rect frame = new Rect();
////		activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
////		int statusBarHeight = frame.top;
//		int statusBarHeight = getStatusHeight(activity);
//		Log.i("TAG", "" + statusBarHeight);
//
//		// 获取屏幕长和高
//		int width = getScreenWidth(activity);
//		int height = getScreenHeight(activity);
//		// 去掉标题栏
//		// Bitmap b = Bitmap.createBitmap(b1, 0, 25, 320, 455);
//		Bitmap b = Bitmap.createBitmap(b1, 0, statusBarHeight, width, height- statusBarHeight);
//		view.destroyDrawingCache();
//		return b;
//	}
    
	
	public static Bitmap takeScreenShot1(Activity activity) 
	{
		// View是你需要截图的View
		View view = (View) activity.getWindow().getDecorView();
		view.setDrawingCacheEnabled(true);
		view.buildDrawingCache();
		Bitmap b1 = view.getDrawingCache();

		// 获取状态栏高度
//		Rect frame = new Rect();
//		activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
//		int statusBarHeight = frame.top;
		int statusBarHeight = getStatusHeight(activity);
		Log.i("TAG", "" + statusBarHeight);

		// 获取屏幕长和高
		int width = getScreenWidth(activity);
		int height = getScreenHeight(activity);
		// 去掉标题栏
		// Bitmap b = Bitmap.createBitmap(b1, 0, 25, 320, 455);
		Bitmap b = Bitmap.createBitmap(b1, 0, statusBarHeight, width, height- statusBarHeight);
		view.destroyDrawingCache();
		return b;
	}
}
